package com.education.teach.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.dn.res.wideget.DnToolbar;
import com.education.teach.R;
import com.education.teach.di.component.DaggerExamDetailComponent;
import com.education.teach.di.module.ExamDetailModule;
import com.education.teach.mvp.contract.ExamDetailContract;
import com.education.teach.mvp.model.bean.AnswerBean;
import com.education.teach.mvp.model.bean.ExamBean;
import com.education.teach.mvp.model.bean.LoginBean;
import com.education.teach.mvp.model.bean.PaperBean;
import com.education.teach.mvp.model.service.ApiService;
import com.education.teach.mvp.presenter.ExamDetailPresenter;
import com.education.teach.mvp.ui.adapter.ExamDetailAdapter;
import com.education.teach.utils.DnCommonUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.jess.arms.utils.Preconditions.checkNotNull;

// 作业详情
public class ExamDetailActivity extends BaseActivity<ExamDetailPresenter> implements ExamDetailContract.View {

    @BindView(R.id.toolbar)
    DnToolbar mToolbar;
    @BindView(R.id.lv_content)
    RecyclerView mRecyclerView;
    @BindView(R.id.swf_pager_list)
    SwipeRefreshLayout mSwipeRereshLayout;
    @BindView(R.id.btn_edit)
    Button btn_edit;
    @BindView(R.id.btn_submit)
    Button btn_submit;
    @BindView(R.id.ll_button)
    LinearLayout ll_button;

    @Inject
    IRepositoryManager mIRepositoryManager;
    @Inject
    RxErrorHandler mRxErrorHandler;

    private String findPaperId = "";
    private PaperBean resultPaper;
    private ExamDetailAdapter mAdapter;

    private LoginBean mLoginBean;
    private List<PaperBean.ResultBean.PaperTypeBean.PapertypeQuestionBean.QuestionBean> mList = new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerExamDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .examDetailModule(new ExamDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_exam_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mToolbar.setMainTitle("答题");
        mToolbar.setToolbarLeftBackImageRes(R.mipmap.top_back);
        mToolbar.setOnLeftTitleClickListener(view -> finish());
        mSwipeRereshLayout.setRefreshing(false);
        mSwipeRereshLayout.setEnabled(false);
        // 取得数据
        Intent intent = this.getIntent();
        ExamBean.ResultBean.QueryListBean.PaperBean paperIn=(ExamBean.ResultBean.QueryListBean.PaperBean)intent.getSerializableExtra("bean");
        findPaperId = paperIn.getId();
        if (paperIn.getAnswerState()==1 || paperIn.getAnswerState() == 2 ){
            ll_button.setVisibility(View.GONE);
        }else{
            ll_button.setVisibility(View.VISIBLE);
        }

        getData(paperIn.getAnswerState());



        btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<PaperBean.ResultBean.PaperTypeBean.PapertypeQuestionBean.QuestionBean> listAnswer=mAdapter.getData();
                List<AnswerBean> listMapAnswer = new ArrayList<AnswerBean>();
                for (int i = 0; i < listAnswer.size(); i++) {
                    PaperBean.ResultBean.PaperTypeBean.PapertypeQuestionBean.QuestionBean bean = listAnswer.get(i);
                    AnswerBean answerBean = new AnswerBean();
                    answerBean.setId(bean.getId());
                    answerBean.setAnswer(bean.getAnswerQes());
                    listMapAnswer.add(answerBean);
                }
                JSONArray jsonArray = new JSONArray();
                String mapJson = JSONArray.toJSONString(listMapAnswer);
                Map<String, String> map = new HashMap<>();
                LoginBean bean = DnCommonUtils.getUserModel(ExamDetailActivity.this);
                map.put("ywbxlh", bean.getResult().getXsXlh());
                map.put("paperId", findPaperId);
                map.put("json", mapJson);

                mIRepositoryManager
                .obtainRetrofitService(ApiService.class)
                .doingHomeWork(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<AnswerBean>(mRxErrorHandler) {
                    @Override
                    public void onNext(AnswerBean answerBean) {
                        EventBus.getDefault().post("refresh", "DO_REFRESH");
                        Toast.makeText(ExamDetailActivity.this, "答案已提交", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
            }
        });

        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String, String> map = new HashMap<>();
                LoginBean bean = DnCommonUtils.getUserModel(ExamDetailActivity.this);
                map.put("yhxlh", bean.getResult().getXlh());
                map.put("paperId", findPaperId);

                mIRepositoryManager
                .obtainRetrofitService(ApiService.class)
                .submitHomeWork(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<AnswerBean>(mRxErrorHandler) {
                    @Override
                    public void onNext(AnswerBean answerBean) {
                        EventBus.getDefault().post("refresh", "DO_REFRESH");
                        Toast.makeText(ExamDetailActivity.this, "已提交批阅", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });

            }
        });
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    /**
     * 将实体POJO转化为JSON
     * @param obj
     * @return
     */
    public static<T> JSONObject objectToJson(T obj) throws JSONException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        // Convert object to JSON string
        String jsonStr = "";
        try {
            jsonStr =  mapper.writeValueAsString(obj);
        } catch (IOException e) {
            throw e;
        }
        return new JSONObject(jsonStr);
    }

    private PaperBean getData(int state) {

        Map<String, String> map = new HashMap<>();
        LoginBean bean = DnCommonUtils.getUserModel(ExamDetailActivity.this);
        if (state != -1){
            map.put("ywbxlh", bean.getResult().getXsXlh());
        }
        map.put("paperId", findPaperId);
        mIRepositoryManager
                .obtainRetrofitService(ApiService.class)
                .doHomeWork(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<PaperBean>(mRxErrorHandler) {
                    @Override
                    public void onNext(PaperBean paperBean) {
                        if (paperBean.getCode() != 1){
                            if (paperBean != null && paperBean.getResult().getPaperType() != null){
                                for (int i = 0; i < paperBean.getResult().getPaperType().size(); i++) {
                                    PaperBean.ResultBean.PaperTypeBean typeBean = paperBean.getResult().getPaperType().get(i);
                                    for (int j = 0; j < typeBean.getPapertypeQuestion().size(); j++) {
                                        PaperBean.ResultBean.PaperTypeBean.PapertypeQuestionBean.QuestionBean bean = typeBean.getPapertypeQuestion().get(j).getQuestion();
                                        mList.add(bean);
                                    }
                                }
                            }
                        }else{
                            Toast.makeText(ExamDetailActivity.this, "服务器异常，请稍后再试", Toast.LENGTH_SHORT).show();
                        }

                        mLoginBean = DnCommonUtils.getUserModel(ExamDetailActivity.this);
//        mSwipeRereshLayout.setOnRefreshListener(this);
                        mRecyclerView.setLayoutManager(new LinearLayoutManager(ExamDetailActivity.this));
                        mAdapter = new ExamDetailAdapter(R.layout.item_detail_exam, mList);
//                        CustomLoadMoreView mLoadMoreView = new CustomLoadMoreView();
//                        mAdapter.setLoadMoreView(mLoadMoreView);
//        mAdapter.setOnLoadMoreListener(this, mRecyclerView);
//                        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
//                        mAdapter.isFirstOnly(true);
                        mRecyclerView.setAdapter(mAdapter);
                    }
                });
        return resultPaper;
    }
}
